package com.wits.platform.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Constants;
//import com.wistronits.lic.LicException;
import com.wits.comet.chat.service.ChatRoomService;
import com.wits.comet.chat.service.CurrentLoginUser;
import com.wits.platform.common.constants.UserType;
import com.wits.platform.common.utils.StringUtil;
import com.wits.platform.entity.Menu;
import com.wits.platform.service.MenuService;
import com.wits.platform.service.UserService;
import com.wits.platform.service.account.LoginCommand;
import com.wits.platform.service.account.ShiroUser;
import com.wits.platform.web.mvc.AjaxResult;


@Controller
public class MainController extends BaseController {

	@Autowired
	private MenuService menuService;

	@Autowired
	private UserService userService;
	
	@Autowired
	private ChatRoomService chatRoomService;
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(@ModelAttribute LoginCommand command) {
		return "login";
	}
	
	@RequestMapping(value = "/entrance")
	public String entrance() {
		return "entrance";
	}
	
	@RequestMapping(value = "/welcome")
	public String welcome(){
		return "main/welcome";
	}
	
	@RequestMapping(value = "/welcomeStudent")
	public String welcomeStudent(){
		return "main/welcomeStudent";
	}	
	
	@RequestMapping(value = "/main", method = { RequestMethod.GET })
	public String main(HttpServletRequest request, Model model)throws Exception {
		if((UserType.TEACHER.getValue()).equals(getCurrentUser().getUserType())){
			model.addAttribute("userType", "tea");
		}
		else
		{
			model.addAttribute("userType", "other");
		}
		return "main/main";

	}
	
	
	@RequestMapping(value = "/teacherHome", method = { RequestMethod.GET })
	public String teacherHome(HttpServletRequest request, Model model)throws Exception {
		return "main/teacherHome";

	}

	@RequestMapping(value = "/studentHome", method = { RequestMethod.GET })
	public String studentHome(HttpServletRequest request, Model model)throws Exception {
		return "main/studentHome";

	}	
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Object login(LoginCommand loginCommand, HttpServletRequest req) {
		AjaxResult result=null;
		if(!validateCaptcha(loginCommand,req)){
			result=ajaxDoneError(this.getText("errors.verifycode.invalid"));
		}else{
			result=doLogin(loginCommand,req);
		}
		return result;
	}
	
    @RequestMapping("/logout")
    public String logout() throws Exception {
        Subject subject=SecurityUtils.getSubject();
        ShiroUser user=(ShiroUser)subject.getPrincipal();
//        chatRoomService.logout(user);
        CurrentLoginUser.getInstance().removeMember(user.getId());
        subject.logout();
        return "redirect:/";
    }

	
	@RequestMapping(value = "/myMenus")
	@ResponseBody
	public Object myMenus(HttpServletRequest request, Model model)throws Exception {
		ShiroUser user=(ShiroUser)SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
		List<Menu> menus=menuService.findMenuByUserId(user.getId());
		return menus.toString();
	}
	
	
    private boolean validateCaptcha(LoginCommand command, HttpServletRequest request){
	    String captchaId = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
	    String response = command.getVerifyCode();
	    return StringUtils.equalsIgnoreCase(captchaId, response);
    }
    
    
    protected AjaxResult doLogin(LoginCommand command, HttpServletRequest request){
    	AjaxResult result=null;
		UsernamePasswordToken token = new UsernamePasswordToken(command.getUserId(),command.getPassword(), command.isRememberMe());
		try {
			this.setLocale(command.getLocale());
			Subject subject=SecurityUtils.getSubject();
			subject.login(token);
			ShiroUser shiroUser=(ShiroUser)subject.getPrincipals().getPrimaryPrincipal();
			userService.updateLoginStatus(shiroUser.getId(),StringUtil.getIpAddr(request));
			result=ajaxDoneSuccess(shiroUser);
		} catch (UnknownAccountException e) {
			result=ajaxDoneError(this.getText("errors.account.invalid"));
		} catch (IncorrectCredentialsException e) {
			result=ajaxDoneError(this.getText("errors.account.invalid"));
		} catch (LockedAccountException e) {
			result=ajaxDoneError(this.getText("errors.account.locked"));
		} catch (ExpiredCredentialsException e) {
			result=ajaxDoneError(this.getText("errors.account.expired"));
//		}catch (LicException e) {
//			e.printStackTrace();
//			result=ajaxDoneError(this.getText("errors.lic.interception"));
		}catch(Exception e){
			e.printStackTrace();
			result=ajaxDoneError();
		}
		return result;
    }
   
   


}
